package com.jc.service.exampleapp.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jc.service.common.exception.ServiceException;
import com.jc.service.exampleapp.entity.ExampleApp;
import com.jc.service.exampleapp.mapper.ExampleAppMapper;
import com.jc.service.exampleapp.model.ExampleAppQueryParam;
import com.jc.service.exampleapp.service.ExampleAppService;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.UUID;

/**
 * 示例应用服务实现类
 * 提供示例应用的业务逻辑实现
 */
@Service
public class ExampleAppServiceImpl implements ExampleAppService {

    /**
     * 示例应用Mapper接口
     */
    private final ExampleAppMapper exampleAppMapper;

    /**
     * 构造函数注入ExampleAppMapper
     * @param exampleAppMapper 示例应用Mapper
     */
    public ExampleAppServiceImpl(ExampleAppMapper exampleAppMapper) {
        this.exampleAppMapper = exampleAppMapper;
    }

    /**
     * 创建示例应用
     * @param exampleApp 示例应用信息
     * @return 创建后的示例应用
     */
    @Override
    public ExampleApp create(ExampleApp exampleApp) {
        // 设置ID和时间
        exampleApp.setId(UUID.randomUUID().toString().replace("-", ""));
        LocalDateTime now = LocalDateTime.now();
        exampleApp.setCreatedAt(now);
        exampleApp.setUpdatedAt(now);
        exampleApp.setDeleted(false);

        // 默认激活状态
        if (exampleApp.getIsActive() == null) {
            exampleApp.setIsActive(true);
        }

        // 插入数据
        int rows = exampleAppMapper.insert(exampleApp);
        if (rows <= 0) {
            throw new ServiceException("创建示例应用失败");
        }

        return exampleApp;
    }

    /**
     * 更新示例应用
     * @param exampleApp 示例应用信息
     * @return 更新后的示例应用
     */
    @Override
    public ExampleApp update(ExampleApp exampleApp) {
        // 检查是否存在
        ExampleApp existing = exampleAppMapper.selectById(exampleApp.getId());
        if (existing == null) {
            throw new ServiceException("示例应用不存在");
        }

        // 更新时间
        exampleApp.setUpdatedAt(LocalDateTime.now());

        // 保留创建时间
        exampleApp.setCreatedAt(existing.getCreatedAt());

        // 更新数据
        int rows = exampleAppMapper.updateById(exampleApp);
        if (rows <= 0) {
            throw new ServiceException("更新示例应用失败");
        }

        return exampleApp;
    }

    /**
     * 根据ID获取示例应用
     * @param id 示例应用ID
     * @return 示例应用信息
     */
    @Override
    public ExampleApp getById(String id) {
        ExampleApp exampleApp = exampleAppMapper.selectById(id);
        if (exampleApp == null) {
            throw new ServiceException("示例应用不存在");
        }
        return exampleApp;
    }

//    @Override
//    public List<ExampleApp> list() {
//        return exampleAppMapper.selectList(null);
//    }
//
//    @Override
//    public IPage<ExampleApp> page(Page<ExampleApp> page) {
//        return exampleAppMapper.selectPage(page, null);
//    }

    /**
     * 根据ID删除示例应用（逻辑删除）
     * @param id 示例应用ID
     * @return 是否删除成功
     */
    @Override
    public boolean deleteById(String id) {
        // 检查是否存在
        ExampleApp existing = exampleAppMapper.selectById(id);
        if (existing == null) {
            throw new ServiceException("示例应用不存在");
        }

        // 逻辑删除
        int rows = exampleAppMapper.deleteById(id);
        return rows > 0;
    }

    /**
     * 根据条件分页查询示例应用
     * @param page 分页参数
     * @param queryParam 查询参数
     * @return 分页结果
     */
    @Override
    public IPage<ExampleApp> getWithPageAndCondition(Page<ExampleApp> page, ExampleAppQueryParam queryParam) {
        LambdaQueryWrapper<ExampleApp> queryWrapper = new LambdaQueryWrapper<>();

        // 添加租户条件
        if (StringUtils.hasText(queryParam.getTenantId())) {
            queryWrapper.eq(ExampleApp::getTenantId, queryParam.getTenantId());
        }

        // 添加名称条件（模糊查询）
        if (StringUtils.hasText(queryParam.getName())) {
            queryWrapper.like(ExampleApp::getName, queryParam.getName());
        }

        if (StringUtils.hasText(queryParam.getCode())) {
            queryWrapper.eq(ExampleApp::getCode, queryParam.getCode());
        }

        if (StringUtils.hasText(queryParam.getDomain())) {
            queryWrapper.eq(ExampleApp::getDomain, queryParam.getDomain());
        }

        // 添加创建时间范围条件
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        if (StringUtils.hasText(queryParam.getCreateTimeStart())) {
            LocalDateTime startTime = LocalDateTime.parse(queryParam.getCreateTimeStart(), formatter);
            queryWrapper.ge(ExampleApp::getCreatedAt, startTime);
        }

        if (StringUtils.hasText(queryParam.getCreateTimeEnd())) {
            LocalDateTime endTime = LocalDateTime.parse(queryParam.getCreateTimeEnd(), formatter);
            queryWrapper.le(ExampleApp::getCreatedAt, endTime);
        }

        // 默认按创建时间降序排序
        queryWrapper.orderByDesc(ExampleApp::getCreatedAt);

        return exampleAppMapper.selectPage(page, queryWrapper);
    }
}